/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution{
public:
  ListNode *removeNthFromEnd(ListNode *head, int n){

    int length = 0;
    ListNode *p = head;

    // 测量长度
    while(p){
      p = p->next;
      ++length;
    }

    if(length <= n || length == 0){
      if(length == n){
        ListNode *temp = head;
        head = head->next;
        delete temp;
        temp = nullptr;

      }
      return head;
    }

    // 人造头结点pre
    ListNode *pre = new ListNode();
    pre->next = head;
    p = head;
    ListNode *k = head;
    while(n - 1){
      k = k->next;
      --n;
    }
    while(k->next && p){
      p = p->next;
      pre = pre->next;
      k = k->next;
    }

    pre->next = p->next;
    delete p, p = nullptr;

    return head;

  }
};